import React from "react";
import { Button, Col, Divider, Drawer, Form, Icon, Input, message, Row, Switch, Select, } from "antd";
import { connect } from "dva";
import styles from "@/pages/KnowledgeGraph/editDrawer/typeNode.less";
import SimilarQuestion from "@/pages/KnowledgeManagement/Overview/EditingKnowledge/similarQuestionForGraph";
import Similar from "@/modules/Similar";
import { userTypeList } from '@/services/geographic';
import { deleteSimilarQuestion } from "@/modules/Similar/deleteSimilarQuestion";
import { knowledgeAtlasNodeDetail } from "@/services/knowledgegraph";
import uniqBy from "lodash/uniqBy";
import UserSession from "@/UserSession";
import RelatedKnowledgeV2 from '@/utils/RelatedKnowledgeV2';

class TypeNodeInfo extends React.Component {
	constructor(props) {
		super(props);
		this.state = {
			visible: false,
			nodeInfo: null,
			isShowSecondDrawer: false, //是否打开更多相似问
			similarQuestions: [],
			stdQuestion: "",
			relatedVisible: false,
			relatedData: [],
			nodeDetail: null,
			similarData: [],
			similarType: "1",
			similarlibData: [],
			isSystem: true,
			userTagList: [],
		};
	}

	componentDidMount() {
		if (this.props.onRef) {
			this.props.onRef(this);
		}
	}

	/**
	 * 打开类别节点编辑框并请求详情
	 */
	openDrawer = (node) => {
		const nodeInfo = node._cfg.model;
		this.setState({ visible: true, nodeInfo, }, () => {
			this.getNodeDetail(nodeInfo);
			this.getUserTagList();
		});
	};

	/**
	 * 获取节点编辑详情
	 */
	getNodeDetail = async (nodeInfo) => {
		const { dispatch } = this.props;
		if (UserSession.isSystemKnowledge()) {
			let res = await knowledgeAtlasNodeDetail({ nodeId: nodeInfo.id });
			// console.log(res);
			this.setState(
				{
					relatedData: res.relateQuestion ? res.relateQuestion.map(item => {
						return { ...item, id: item.qaIdRel };
					}) : [],
					nodeDetail: res,
					isSystem: res.relateQaSource && res.relateQaSource == 1 ? false : true,
				},
				() => {
					this.SimilarQuestion.setStandQuestion(res.basicQuestion);
					this.SimilarQuestion.setQuestions(res.alikeQuestion ? res.alikeQuestion : []);
					this.RelatedKnowledge.setRelatedList(
						res.relateQuestion ? res.relateQuestion.map(item => {
							return { ...item, id: item.qaIdRel };
						}) : []
					);
				}
			);
		} else {
			dispatch({
				type: "nodeEdit/getNodeDetailByNodeId",
				payload: {
					id: nodeInfo.id,
					urlPrefix: UserSession.isSystemKnowledge() ? 1 : null,
				},
				callback: (res) => {
					console.log(res);
					this.setState(
						{
							relatedData: res.relateQuestion ? res.relateQuestion.map(item => {
								return { ...item, id: item.qaIdRel };
							}) : [],
							nodeDetail: res,
							isSystem: res.relateQaSource && res.relateQaSource == 1 ? false : true,
						},
						() => {
							this.SimilarQuestion.setStandQuestion(res.basicQuestion);
							this.SimilarQuestion.setQuestions(res.alikeQuestion ? res.alikeQuestion : []);
							this.RelatedKnowledge.setRelatedList(
								res.relateQuestion ? res.relateQuestion.map(item => {
									return { ...item, id: item.qaIdRel };
								}) : []
							);
						}
					);
				},
			});
		}
	};

	/**
	 * 关闭类别节点编辑框
	 */
	closeDrawer = () => {
		this.props.form.resetFields();
		this.setState({
			visible: false,
			nodeInfo: null,
			isShowSecondDrawer: false, //是否打开更多相似问
			similarQuestions: [],
			stdQuestion: "",
			relatedVisible: false,
			relatedData: [],
		});
	};

	/**
	 * 打开更多相似问
	 */
	showMoreQuestionDrawer = (similarQuestions, stdQuestion) => {
		this.setState({ isShowSecondDrawer: true, similarQuestions, stdQuestion });
	};

	/**
	 * 关闭更多相似问
	 */
	closeMoreQuestionDrawer = () => {
		let data = this.SimilarQuestionMore.state.moreQuestions;
		let stdQuestion = this.SimilarQuestionMore.getStdQuestionForSecondDrawer();
		this.setState({ similarQuestions: data, isShowSecondDrawer: false }, () => {
			this.SimilarQuestion.setQuestions(data);
			this.SimilarQuestion.setStandQuestion(stdQuestion);
		});
	};

	/**
	 * 打开关联知识点
	 */
	openRelatedKnowledgeModal = () => {
		const { relatedData } = this.state;
    this.RelatedKnowledge.openAndInit(relatedData)
	};

	/**
	 * 关闭关联知识点
	 */
	closeRelatedModal = () => {
		this.setState({ relatedVisible: false });
	};

	/**
	 * 获取选中的关联知识点
	 * @param data
	 */
	getRelatedList = (data) => {
		// console.log(data);
		this.setState({ relatedData: data });
	};

	/**
	 * 删除关联知识点
	 * @param id
	 */
	removeRelatedData = (id) => {
		let { relatedData } = this.state;
		const newData = relatedData.filter((item) => item.id != id);
		this.setState({ relatedData: newData, }, () => {
			this.RelatedKnowledge.setRelatedList(newData);
		});
	};

	/**
	 * 上移关联知识点
	 * @param index
	 */
	upRelatedData = (index) => {
		const arr = this.state.relatedData;
		if (index !== 0) {
			arr[index] = arr.splice(index - 1, 1, arr[index])[0];
		} else {
			arr.push(arr.shift());
		};
		this.setState({ relatedData: arr });
	};

	/**
	 * 保存节点详情
	 */
	saveNodeDetail = () => {
		const { form, atlasId } = this.props;
		const { nodeInfo, relatedData, similarData, similarType, similarlibData, userTagList } = this.state;
		const that = this;
		form.validateFields((errors, values) => {
			if (!errors) {
				const { dispatch } = that.props;
				const questionObj = that.SimilarQuestion.submitQuestions();
				const relateQAs = relatedData.map((item) => item.id);
				let userTagIdList = [];
				if (values.userType && values.userType.length > 0) {
					userTagList.forEach(item => {
						if (values.userType.indexOf(item.id) > -1) {
							userTagIdList.push({ id: item.id, tagName: item.tagName });
						}
					})
				};
				let obj = {
					basicQuestion: questionObj.stdQuestion,
					alikeQuestion: questionObj.questions,
					disabled: values.disabled == undefined ? false : !values.disabled,
					sensitive: values.sensitive,
					guide: values.guide,
					relateQuestionIds: relateQAs,
					relateQaSource: this.state.isSystem ? 0 : 1,
					title: values.title,
					id: nodeInfo.id,
					atlasId,
					userTagIdList,
				};
				let disabled = values.disabled == undefined ? false : !values.disabled;
				dispatch({
					type: "nodeEdit/editNodeInfo",
					payload: obj,
					callback: (res) => {
						if (typeof res.code !== 'undefined' && res.code !== 0) {
							// message["error"](`${res.message}`);
						} else {
							message.info(res.msg);
							this.closeDrawer();
							this.props.resetNodeTitle(values.title, disabled);
						}
					},
				});
			}
		});
	};

	closeSimilar = (data, type) => {
		let { similarType, similarData, similarlibData } = this.state;
		similarType = type;
		let arr = [];
		data.map((item) => {
			arr.push(item.question);
		});
		if (type == "2") {
			similarlibData = uniqBy(similarlibData.concat(data), "id");
		} else {
			similarData = uniqBy(similarData.concat(data), "id");
		};
		this.setState({ similarData, similarType, similarlibData }, () => {
			if (this.SimilarQuestion && this.SimilarQuestion.pushSimilarQuestion) {
				this.SimilarQuestion.pushSimilarQuestion(arr, data);
			};
			if (this.SimilarQuestionMore && this.SimilarQuestionMore.pushSimilarQuestion) {
				this.SimilarQuestionMore.pushSimilarQuestion(arr, data);
			};
		});
	};

	/* 获取用户类型-筛选框 */
	getUserTagList = async () => {
		const res = await userTypeList({ current: 1, size: 999999 });
		this.setState({ userTagList: res.records ? res.records : [], });
	};

	similarExtensionAsk = (data) => {
		if (this.SimilarQuestion) {
			this.SimilarQuestion.similarExtensionAsk(data)
		};
		if (this.SimilarQuestionMore) {
			this.SimilarQuestionMore.similarExtensionAsk(data)
		};
	}

	render() {
		const {
			visible, nodeInfo, isShowSecondDrawer, similarQuestions, stdQuestion,
			relatedVisible, relatedData, nodeDetail, isSystem, userTagList,
		} = this.state;
		const { getFieldDecorator } = this.props.form;
		const formItemLayout = {
			labelCol: { span: 4 },
			wrapperCol: { span: 16 },
		};
		const layoutForOffset = {
			labelCol: { span: 4 },
			wrapperCol: { span: 16, offset: 4 },
		};

		return (
			<Drawer
				title={nodeDetail ? nodeDetail.title : ""}
				width={780}
				onClose={this.closeDrawer}
				visible={visible}
				bodyStyle={{ paddingBottom: 80 }}
				destroyOnClose
			>
				<Form>
					<div className={styles.label}>基础设置</div>
					<Form.Item label='标题' {...formItemLayout}>
						{getFieldDecorator("title", {
							rules: [{ required: true, message: "标题不能为空" }],
							initialValue: nodeDetail ? nodeDetail.title : "",
						})(
							<Input
								placeholder='标题'
								className={styles.inputItem}
								maxLength={100}
								disabled={!UserSession.isSystemKnowledge() ? false : true}
							/>
						)}
					</Form.Item>
					<Form.Item label='引导话术' {...formItemLayout}>
						{getFieldDecorator("guide", {
							initialValue: nodeDetail ? nodeDetail.guide : "",
						})(
							<Input.TextArea
								placeholder='引导话术'
								className={styles.inputItem}
								maxLength={100}
								disabled={!UserSession.isSystemKnowledge() ? false : true}
							/>
						)}
					</Form.Item>
					{UserSession.isSystemDataKnowledge() ? null : (
						<Form.Item label='是否启用' {...formItemLayout}>
							{getFieldDecorator("disabled", {
								valuePropName: "checked",
								initialValue: nodeDetail ? !nodeDetail.disabled : undefined,
							})(<Switch checkedChildren='启用' unCheckedChildren='禁用' />)}
						</Form.Item>
					)}
					{/* <Form.Item label='敏感状态' {...formItemLayout}>
						{getFieldDecorator("sensitive", {
							valuePropName: "checked",
							initialValue: nodeDetail ? nodeDetail.sensitive : "",
						})(<Switch checkedChildren='敏感' unCheckedChildren='非敏感' />)}
					</Form.Item> */}
					{!UserSession.isAdmin() && !UserSession.isSystemKnowledge() && nodeDetail && nodeDetail.graphNodeType !== 0 ? (
						<Form.Item label='适用标签' {...formItemLayout}>
							{getFieldDecorator("userType", {
								initialValue: nodeDetail && nodeDetail.userTagIdList.length > 0 ? nodeDetail.userTagIdList.map(item => item.id) : []
							})(
								<Select mode="multiple" suffixIcon={<Icon type="clock-circle" />} className="tagSelect">
									{userTagList && userTagList.length > 0 ? (
										userTagList.map(item => {
											return <Select.Option value={item.id} key={item.id} item={item}>{item.tagName}</Select.Option>
										})
									) : null}
								</Select>
							)}
						</Form.Item>
					) : ('')}
					<Divider />
					<div className={styles.label}>问题</div>
					<SimilarQuestion
						showMoreQuestion={this.showMoreQuestionDrawer}
						secondDrawer={isShowSecondDrawer}
						similarQuestionsList={similarQuestions}
						onRef={(ref) => (this.SimilarQuestion = ref)}
						stdQuestion={stdQuestion}
						authority={2}
						slotData={[]}
						questionId={nodeInfo?.id}
						similarRef={this.similarRef}
					/>
					<Row style={{ margin: "10px 0px" }}>
						<Col span={4}>
							<div className={styles.label}>关联问题</div>
						</Col>
						<Col span={20} style={{ textAlign: 'right' }}>
							{UserSession.isSystemKnowledge() ? null : (
								<Button
									type='primary'
									onClick={this.openRelatedKnowledgeModal}
									style={{ backgroundColor: "#ffffff", color: '#3E5BFF', borderColor: '#6478FF', borderRadius: '16px' }}
								>
									添加关联知识点
								</Button>
							)}
						</Col>
					</Row>
					<Form.Item style={{ marginLeft: 80 }}>
						{relatedData.map((item, index) => {
							return (
								<div key={index} style={{ margin: "10px 0", position: 'relative', width: 'calc(100% + 58px)' }}>
									{item.relateType === 1 ? (
										<span className={styles.reQaType}>问答</span>
									) : item.relateType === 2 ? (
										<span className={styles.reQaType}>导图</span>
									) : item.relateType === 3 ? (
										<span className={styles.reQaType}>多轮</span>
									) : item.relateType === 4 ? (
										<span className={styles.reQaType}>表单</span>
									) : null}
									<div className={styles.relQaValue} title={item.basicQuestion}>{item.basicQuestion}</div>
									{UserSession.isSystemKnowledge() && isSystem ? null : (
										<>
											<Icon
												type='close-circle'
												style={{ margin: "0px 10px", fontSize: "20px", verticalAlign: 'middle' }}
												onClick={() => this.removeRelatedData(item.id)}
											/>
											{index != 0 ? (
												<span className={styles.relOptionUpBox}>
													<Icon type='arrow-up' style={{ fontSize: "12px" }} onClick={() => this.upRelatedData(index)} />
												</span>
											) : null}
										</>
									)}
								</div>
							);
						})}
					</Form.Item>
				</Form>
				<Drawer
					title={"更多相似问"}
					placement='right'
					closable
					onClose={this.closeMoreQuestionDrawer}
					visible={isShowSecondDrawer}
					width={760}
					destroyOnClose
				>
					<SimilarQuestion
						showMoreQuestion={this.showMoreQuestionDrawer}
						secondDrawer={isShowSecondDrawer}
						similarQuestionsList={similarQuestions}
						stdQuestion={stdQuestion}
						onRef={(ref) => (this.SimilarQuestionMore = ref)}
						authority={2}
						slotData={[]}
						questionId={nodeInfo?.id}
						similarRef={this.similarRef}
					/>
				</Drawer>
        <RelatedKnowledgeV2 
          onRef={ref => this.RelatedKnowledge = ref}
          applicationId={''}
          chooseType='mutiple'
          getRelatedList={this.getRelatedList}
        />
				<Similar
					onRef={(ref) => (this.similarRef = ref)}
					questionId={nodeInfo?.id}
					onClose={this.closeSimilar}
					question={stdQuestion}
					similarExtensionAsk={this.similarExtensionAsk}
				/>
				<div style={{ position: "absolute", right: 0, bottom: 0, width: "100%", borderTop: "1px solid #e9e9e9", padding: "10px 16px", background: "#fff", textAlign: "right" }}>
					<Button onClick={this.closeDrawer} style={{ marginRight: 8 }}>取消</Button>
					<Button onClick={this.saveNodeDetail} type='primary'>保存</Button>
				</div>
			</Drawer>
		);
	}
}

export default connect(({ user }) => ({
	currentUser: user.currentUser,
}))(Form.create()(TypeNodeInfo));
